<template>
	<div>
		<div class="container">
			<a-layout>
				<a-layout-sider width="400" theme="light">
					<div class="pe-4">
						<a-card title="数据字典">
							<template #extra>
								<a-button type="link" @click="addDictionary(0)">
									<plus-outlined />新增
								</a-button>

								<template v-if="rootDictionary.id">
									<a-divider type="vertical" />
									<a-button type="link" @click="editDictionary(rootDictionary)">
										<edit-outlined />修改
									</a-button>
									<a-divider type="vertical" />

									<a-popconfirm title="确定要删除选中的记录吗？" ok-text="是" cancel-text="否" @confirm="deleteDictionary(rootDictionary.id, 0)">
										<a-button danger type="link">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</template>
							</template>

							<a-button v-for="(item, index) in rootDictionaryList" :key="index" :type="item.id === rootDictionary.id ? 'primary' : ''" block class="dict-item" @click="searchState={};rootDictionary=item">
								{{ item.name }}
								<span>{{ item.code }}</span>
							</a-button>
						</a-card>
					</div>
				</a-layout-sider>

				<a-layout-content style="background:#fff">
					<div class="toolbar">
						<a-form ref="searchRef" layout="inline" :model="searchState" @finish="loading=true;initData(rootDictionary.id)">
							<a-form-item label="名称">
								<a-input v-model:value="searchState.name" placeholder="请输入" allow-clear></a-input>
							</a-form-item>

							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>

									<a-tooltip>
										<template #title>请先选择左侧数据字典</template>

										<a-button :disabled="!rootDictionary.id" @click="addDictionary(rootDictionary.id)">
											<plus-outlined />添加
										</a-button>
									</a-tooltip>
								</a-space>
							</a-form-item>
						</a-form>
					</div>

					<div class="mt-2">
						<h2 class="my-4">{{ rootDictionary.name }}</h2>

						<!--获取数据后重新渲染表格，否则defaultExpandAllRows获取动态数据的情况下无效-->
						<!-- default-expand-all-rows true默认展开子表 -->
						<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" :pagination="false" row-key="id" :data-source="dictionaryTree" :loading="loading">
							<template #bodyCell="{ column, record }">
								<template v-if="column.key === 'operation'">
									<a-space>
										<a-button type="link" @click="addDictionary(record.id)">
											<plus-outlined />添加子数据
										</a-button>

										<a-button type="link" @click="editDictionary(record)">
											<edit-outlined />修改
										</a-button>
										<a-button type="link" style="color:#ff7875" @click="deleteDictionary(record.id, rootDictionary.id)">
											<delete-outlined />删除
										</a-button>
									</a-space>
								</template>
							</template>
						</a-table>
					</div>
				</a-layout-content>
			</a-layout>

			<a-modal v-model:visible="visible" :width="400" :title="`${formState.id ? '修改' : '添加'}数据`" @ok="saveDictionary">
				<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '80px' } }}">
					<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
						<a-input v-model:value="formState.name" />
					</a-form-item>

					<a-form-item v-if="formState.parent_id === 0" label="编码" name="code">
						<a-input v-model:value="formState.code" />
					</a-form-item>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>
<script setup>
import { ref, getCurrentInstance, watch, onMounted, computed } from "vue";
const { proxy } = getCurrentInstance();

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";

import { post, listToTree } from "../utils";

const addDictionary = parentId => {
	formState.value = {
		parent_id: parentId
	};
	visible.value = true;
};

const editDictionary = record => {
	formState.value = { ...record };
	visible.value = true;
};

const deleteDictionary = (id, rootId) => {
	post("dictionary/delete", { id }).then(() => {
		proxy.$message.success("删除成功");

		if (rootId === 0) {
			rootDictionary.value = {};
		}

		initData(rootId);
	});
};

const rootDictionary = ref({});

const searchState = ref({});

const visible = ref(false);
const formState = ref({});

const formRef = ref();

const rootDictionaryList = ref([]);

const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 680,
	y: document.documentElement.clientHeight - 400
}));

const loading = ref(false);
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 160,
		align: "left",
		fixed: "left"
	},
	{
		title: "名称",
		dataIndex: "name",
		sorter: false,
		width: 300,
		ellipsis: true
	},
	{
		title: "编码",
		dataIndex: "code",
		sorter: false,
		width: 300,
		ellipsis: true
	},
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 240,
		align: "center"
	}
];
const dictionaryTree = ref([]);

const initData = (parentId = 0) => {
	loading.value = true;

	if (parentId === 0) {
		post("dictionary", { parent_id: 0 }).then(data => {
			loading.value = false;
			rootDictionaryList.value = data;

			if (!rootDictionary.value?.id) rootDictionary.value = data[0] || {};
		});
	} else {
		const { name, code } = searchState.value;
		post("dictionary", { root_id: parentId, name, code }).then(data => {
			loading.value = false;
			dictionaryTree.value = listToTree(JSON.parse(JSON.stringify(data)), parentId);
		});
	}
};

onMounted(() => {
	initData(0);
});

const saveDictionary = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };

			post("dictionary/save", params)
				.then(data => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;

					if (params.parent_id === 0) {
						rootDictionary.value = params;

						initData(0);

						if (data.id) rootDictionary.value = data;
					} else {
						initData(rootDictionary.value.id);
					}
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});

watch(rootDictionary, value => {
	const { id } = value;
	if (!id) return;

	initData(id);
});
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}

.dict-item {
	display: flex;
	justify-content: space-between;

	& + .dict-item {
		margin-top: 15px;
	}
}
</style>